package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 根据条件分页查询文章数据
     *
     * @param wmNewsPageReqDto
     * @return
     */
    @Override
    public ResponseResult listWmNews(WmNewsPageReqDto wmNewsPageReqDto) {
        //1. 校验并修正数据
        if(null == wmNewsPageReqDto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNewsPageReqDto.checkParam(); //修正数据

        //3. 根据分页方法的提示设置分页参数
        IPage<WmNews> page = new Page<>(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize());

        //4. 根据分页方法的提示设置查询的条件
        LambdaQueryWrapper<WmNews> queryWrapper = new LambdaQueryWrapper<>();
        if(null != wmNewsPageReqDto.getStatus()){
            queryWrapper.eq(WmNews::getStatus, wmNewsPageReqDto.getStatus());
        }

        if(null != wmNewsPageReqDto.getBeginPubDate() && null != wmNewsPageReqDto.getEndPubDate()){
            queryWrapper.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        }

        if(null != wmNewsPageReqDto.getChannelId()){
            queryWrapper.eq(WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        }

        if(StringUtils.isNotEmpty(wmNewsPageReqDto.getKeyword())){
            queryWrapper.like(WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        }

        //设置当前登录的用户
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        //设置排序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        //2. 调用service的分页方法完成分页的查询
        page(page,queryWrapper);

        //5. 封装并返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(wmNewsPageReqDto.getPage(),
                wmNewsPageReqDto.getSize(),
                (int)page.getTotal());
        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;
    }

    /**
     * 新增或者更新文章
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDto dto) throws TesseractException, IOException {
        //1. 校验参数 如果不合法返回501
        if(null == dto || StringUtils.isEmpty(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 保存或者更新文章数据
        WmNews wmNews = saveOrUpdateWmNes(dto);

        //如果是草稿则直接返回
        if(WmNews.Status.NORMAL.getCode() == dto.getStatus()){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3. 抽取内容中的图片数据
        List<String> imageUrls = ectractUrlInfo(dto.getContent());

        //4. 保存内容图片和素材之间的关系
        saveRelativeInfoForContent(imageUrls, wmNews.getId());
        //5. 保存封面图片和素材之间的关系
        saveRelativeInfoForCover(dto,wmNews,imageUrls);

        //5.1 异步调用审核方法完成文章的审核和同步
        //autoScanService.autoScanWmNews(wmNews.getId());

        //5.1 发布文章以后 添加审核的任务
        wmNewsTaskService.addWmNewsToTask(wmNews);

        //6. 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面和素材之间的关系
     * @param dto
     * @param wmNews
     * @param imageUrls
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> imageUrls) {
        //1. 获取封面图片
        List<String> images = dto.getImages();

        //2. 如果封面类型是自动 则需要按照规则生成封面图片
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            if(null == imageUrls || imageUrls.size() == 0){
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if(imageUrls.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_COVER_REFERENCE);
                images = imageUrls.stream().limit(1).collect(Collectors.toList());
            }else{
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imageUrls.stream().limit(3).collect(Collectors.toList());
            }

            //保存修改的文章数据
            updateById(wmNews);
        }

        //3. 判断封面封面图片是否不能空 如果不为空则保存素材和封面之间的关系
        saveRelativeInfo(images, wmNews.getId(), WemediaConstants.COLLECT_MATERIAL);
    }

    private void saveRelativeInfo(List<String> images, Integer wmNews, Short collectMaterial) {
        if (null != images && images.size() > 0) {
            //3.1 对图片数据进行去重
            images = images.stream().distinct().collect(Collectors.toList());

            //3.2 通过地址查询所有的素材数据
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images.toArray()));

            //3.3 判断是否是否被别人删除过 如果被别人删除过则抛出异常
            if (null == wmMaterials || wmMaterials.size() == 0 || images.size() != wmMaterials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            //3.4 调用mapper方法完成数据的批量插入
            List<Integer> ids = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
            wmNewsMaterialMapper.batchInert(ids, wmNews, collectMaterial);
        }
    }

    /**
     * 保存内容图片和素材之间的关系
     * @param imageUrls
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> imageUrls, Integer newsId) {
        //1. 判断内容中是否有图片
        saveRelativeInfo(imageUrls, newsId, WemediaConstants.CANCEL_COLLECT_MATERIAL);
    }

    private List<String> ectractUrlInfo(String content) {
        List<String> list = new ArrayList<>();
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        if(null != mapList && mapList.size() > 0){
            for (Map map : mapList) {
                if("image".equals(map.get("type").toString())){
                    list.add(map.get("value").toString());
                }
            }
        }

        return list;
    }

    private WmNews saveOrUpdateWmNes(WmNewsDto dto) {
        //1. 创建pojo对象
        WmNews wmNews = new WmNews();

        //2. 把dto中的数据拷贝到pojo
        BeanUtils.copyProperties(dto, wmNews);

        //3. 补齐拷贝不成功的数据
        //如果文章类型是自动不能存储-1 因为字段被unsigned 所以需要设置位空
        if(WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //处理图片
        if(null != dto.getImages() && dto.getImages().size() > 0){
            //[a.png,b.png] --> a.png,b.png
            wmNews.setImages(StringUtils.join(dto.getImages().toArray(), ","));
        }

        //设置其他基础字段
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short)1);
        wmNews.setSubmitedTime(new Date());

        //4. 判断是否有id 如果有则是修改 如果没有则是新增
        if(null == wmNews.getId()){
            //新增
            save(wmNews);
        }else{
            //修改
            //1. 删除文章和素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));

            //2. 更新文章数据
            updateById(wmNews);
        }

        return wmNews;
    }
}
